<template>
  <!-- <ContainerGroup> -->
  <base-page v-bind="basePageConfig">
    <template #searchBar>
      <FilterForm
        ref="filterForm"
        :elements="elements"
        noimmediate
        @submit="submit"
      />
    </template>
    <template #content>
      <div class="control-box">
        <Button icon="add" @click="insert">新建</Button>

      </div>
      <Table
        :data="tableData"
        :pagination="pagination"
        :loading="tableLoading"
        :columns="tableDataEL"
        @paginationChange="paginationChange"
        @rowSelection="rowSelection"
      >

        <template #status="scope">
          <div>
            <el-switch
              v-model="scope.row.status"
              active-color="#217DFA"
              inactive-color="#DCDCDC"
              active-value="0"
              inactive-value="1"
              @change="switchChange(scope.row)"
            />
          </div>
        </template>

        <template #action="scope">
          <el-tooltip class="item" effect="dark" content="编辑" placement="top">
            <i class="el-icon-edit action" @click="edit(scope.row)" />
            <!-- <i class="el-icon-edit action" /> -->
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="删除" placement="top">
            <i class="el-icon-delete action" @click="remove(scope.row)" />
            <!-- <i class="el-icon-delete action" /> -->
          </el-tooltip>
        </template>
      </Table>
      <Drawer
        :visible="drawerVisible"
        :title="drawerTitle"
        :footer-btns="drawerController"
        width="30%"
        @cancel="drawerCancel"
        @submit="drawerSubmit"
        @continueAdd="continueAdd"
      >
        <div class="draw-body">
          <el-form
            ref="formData"
            label-width="80px"
            :model="formData"
            :rules="rules"

            @keyup.enter.native="drawerSubmit('formData')"
          >
            <el-form-item label="工号" prop="card">

              <el-input
                v-model="formData.card"
                oninput="value=value.replace(/[^\d.]/g,'')"
                style="width: 240px"
                size="small"
              />
            </el-form-item>

            <el-form-item label="姓名" prop="name">
              <el-input
                v-model="formData.name"
                style="width: 240px"
                size="small"
              />
            </el-form-item>

            <el-form-item label="角色" prop="role">
              <el-select
                v-model="role"
                style="width: 240px"
                size="small"
                @change="$forceUpdate()"
              >
                <el-option
                  v-for="(item,index) in roleList"
                  :key="index"
                  :label="item.roleName"
                  :value="item.roleId+'/'+item.roleName"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="密码" prop="password">
              <el-input

                v-model="formData.password"
                type="password"
                style="width: 240px"
                size="small"
              />
            </el-form-item>

            <el-form-item label="账号状态" prop="status">
              <el-switch
                v-model="formData.status"
                active-color="#217DFA"
                inactive-color="#DCDCDC"
                active-value="0"
                inactive-value="1"
                size="small"
              />
            </el-form-item>
          </el-form>
        </div>
      </Drawer>

    </template>
  </base-page>
</template>

<script>
import baseFilterTable from '../../mixins/baseFilterTable'
import baseInfo from '../../utils/config'
import { findPage, saveOrUpdate, remove, userfindPage, createUser, getRoleList, removeUser, renew, replaceStatus } from '../../utils/apis/invoiceSystem'

export default {
  name: '',
  components: {},
  mixins: [baseFilterTable],
  data() {
    return {
      pagination: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      rules: {
        card: [
          { required: true, message: '请输入工号', trigger: 'change' }
        ],
        name: [
          { required: true, message: '请输入姓名', trigger: 'change' }
        ],
        role: [
          { required: true, message: '请选择角色', trigger: 'change' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'change' }
        ],
        status: [
          { required: true, message: '请选择账号状态', trigger: 'change' }
        ]

      },
      formData: {
        card: '',
        name: '',
        role: '',
        status: '',
        password: ''
      },
      basePageConfig: {
        searchBarShow: true
      },
      form: {
        noteCode: ''
      },
      elements: [
        {
          label: '工号',
          type: 'Input',
          format: ' ',
          key: 'workNum',
          value: ''
        },
        {
          label: '姓名',
          type: 'Input',
          format: ' ',
          key: 'name',
          value: ''
        },
        {
          label: '角色',
          type: 'Select',
          format: ' ',
          key: 'role',
          value: '',
          options: []
        },
        {
          label: '账号状态',
          type: 'Select',
          format: '',
          key: 'accountStatus',
          value: '',
          options: [
            {
              label: '启用',
              value: '0'
            },
            {
              label: '停用',
              value: '1'
            }
          ]
        }

      ],
      tableData: [],
      tableDataEL: [

        {
          dataIndex: 'card',
          title: '工号'

        },
        {
          dataIndex: 'name',
          title: '姓名',
          type: ''
        },
        {
          dataIndex: 'roleName',
          title: '角色'

        },
        {
          dataIndex: 'status',
          title: '账号状态',
          type: 'otherTag'

        },

        {
          dataIndex: 'action',
          title: '操作',
          align: 'center',
          type: 'otherTag',
          width: 180
        }
      ],
      drawerController: [

        {
          text: '提交',
          trigger: 'submit',
          type: 'primary'
        }

      ],
      dialogController: [
        {
          text: '取消',
          trigger: 'cancel'
        }
      ],
      attachmentSrc: '',
      dropList: [
        {
          label: '批量导出',
          value: '1',
          handlerClick: this.exportSelect
        },
        {
          label: '全部导出',
          value: '2',
          handlerClick: this.exportAll
        }
      ],
      dropDownLoading: false,
      drawerVisible: false,
      imgList: [],
      currentId: '',
      isEdit: false,
      multipleSelection: [],
      roleList: [],
      role: ''
    }
  },
  created() {
    this.getData()
    this.getRole()
  },
  mounted() {},
  methods: {

    async switchChange(row) {
      const params = {
        status: row.status,
        card: row.card
      }
      const { data } = await replaceStatus(params)
      if (data.code === 200) {
        this.getData()
        this.$message.success('编辑成功')
      } else {
        this.$message.error('编辑失败')
      }
    },

    resolveBug() {
      console.log(this.formData.role)
      // this.$forceUpdate()
    },
    getRole() {
      getRoleList().then(res => {
        if (res.data.code === 200) {
          this.roleList = res.data.data

          res.data.data.forEach(element => {
            this.elements[2].options.push({
              label: element.roleName,
              value: element.roleId
            })
          })
        } else {
          console.log('87y87u')
        }
      })
    },

    rowSelection(data) {
      this.multipleSelection = data
    },

    continueAdd() { // 继续提交

    },
    submit(val) {
      this.pagination.pageNum = 1
      this.getData(val)
    },

    paginationChange(val) {
      this.pagination.pageNum = val.current
      this.pagination.pageSize = val.pageSize
      this.getData()
    },
    handleNodeClick() {},
    getData(val) {
      console.log(val)
      const params = {
        num: this.pagination.pageNum,
        size: this.pagination.pageSize,
        status: val ? val.accountStatus : '',
        roleId: val ? val.role : '',
        name: val ? val.name : '',
        card: val ? val.workNum : ''
      }

      userfindPage(params).then((res) => {
        console.log(res)
        if (res.data.code === 200) {
          this.tableData = res.data.data.records
          this.pagination.total = res.data.data.total
        } else {
          console.log('g')
        }
      })
    },
    insert() {
      this.$refs.formData.resetFields()
      this.isEdit = false
      this.drawerTitle = '新增'
      this.drawerVisible = true
      // this.setFocus()
    },
    edit(row) {
      console.log(row)
      this.isEdit = true
      this.currentId = row.id
      this.drawerTitle = '编辑'
      this.drawerVisible = true
      this.formData = JSON.parse(JSON.stringify(row))
      this.role = JSON.parse(JSON.stringify(row)).roleId + '/' + JSON.parse(JSON.stringify(row)).roleName
      this.formData.role = JSON.parse(JSON.stringify(row)).roleId + '/' + JSON.parse(JSON.stringify(row)).roleName
    },
    // 设置聚焦
    setFocus() {
      this.$nextTick(() => {
        this.$refs.ticketCode.$el.children[0].focus()
      })
    },
    // 扫描结果填充
    inputInput(val) {
      if ((val.split('').filter(k => k === '/').length) > 1) {
        const res = val.split('/').splice(-3, 3)
        this.formData.ticketCode = res[0]
        this.formData.ticketNumber = res[1]
        this.formData.checkCode = res[2]
      } else {
        this.formData.ticketCode = val.replace(/[^\d.]/g, '')
      }
    },
    remove(row) {
      this.$confirm({
        content: '请输入立即删除，确认删除',
        title: '提示',
        action: 'delete',

        okFn: async(res) => {
          const params = {
            id: row.id
          }

          removeUser(params).then(res => {
            if (res.data.code === 200) {
              this.$message.success('删除成功')
              this.getData()
            } else {
              this.$message.warning(res.data.msg)
            }
          })

          console.log(params)
        },
        cancelFn: (res) => {
          console.log('取消')
        }
      })
    },
    showAttachment(item) {
      this.dialogTitle = item.fileName
      this.attachmentSrc = `${baseInfo.BASE_URL}upload/${item.fileUrl}`
      if (
        item.fileName.indexOf('.xlsx') === -1 &&
        item.fileName.indexOf('.xls') === -1
      ) {
        this.dialogVisible = true
      }
    },
    drawerSubmit() {
      const params = {
        name: this.formData.name,
        card: this.formData.card,
        password: this.formData.password,
        roleId: this.role.split('/')[0],
        status: this.formData.status
      }
      this.formData.role = this.role
      this.$refs.formData.validate((valid) => {
        if (valid) {
          if (this.isEdit) {
            params.id = this.currentId

            renew(params).then((res) => {
              if (res.data.code === 200) {
                this.$message.success('修改成功')
                this.getData()
                this.drawerVisible = false
              } else {
                this.$message.warning(res.data.msg)
                this.drawerVisible = false
              }
            })
          } else {
            createUser(params).then((res) => {
              if (res.data.code === 200) {
                this.$message.success('新增成功')
                this.drawerVisible = false
                this.getData()
                this.$refs.formData.resetFields()
                // this.setFocus()
                // this.drawerVisible = false
              } else {
                this.$message.warning(res.data.msg)
                this.drawerVisible = false
              }
            })
          }
        } else {
          return false
        }
      })
    },
    dialogCancel() {
      this.dialogVisible = false
    },
    success(res) {
      this.$message.success('提交成功')
      this.$btnLoading('drawerController', 'submit', false)
      this.drawerCancel()
    },
    fail(res) {
      this.$message.error('提交失败')
      this.$btnLoading('drawerController', 'submit', false)
    },
    exportSelect() {
      console.log('批量导出')
      this.dropDownLoading = true
      setTimeout(() => {
        this.dropDownLoading = false
      }, 1000)
    },
    exportAll() {
      console.log('全部导出')
      this.dropDownLoading = true
      setTimeout(() => {
        this.dropDownLoading = false
      }, 1000)
    },
    async fileDel(item, index) {},
    drawerCancel() {
      this.drawerVisible = false
      this.imgList = []
      this.getData()
    }
  }
}
</script>

<style lang="less" scoped>
.input-item {
  margin-bottom: 20px;
}
.control-box {
  margin-bottom: 10px;
  display: flex;
}
.action {
  font-size: 16px;
  margin-right: 8px;
  cursor: pointer;
  color: #2165f9;
}
.action:last-of-type {
  margin-right: 0;
}
.attachment {
  color: #2165f9;
  cursor: pointer;
  text-decoration: underline;
  margin-right: 8px;
}
.draw-body {
  padding: 12px;
}
.frame {
  height: calc(80vh - 40px);
  width: 900px;
}
/deep/ .ck-dialog-container {
  top: 1vh !important;
}
.upload-file-wrap {
  display: flex;
  flex-wrap: wrap;
}
</style>
